package sample.model;

import com.jcraft.jsch.Session;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.Callable;

import static sample.util.SSHUtils.execCommandByJSch;

public class StartMonitor implements Callable<String> {
    private HashMap<String, String[]> serverMap = new HashMap<String, String[]>();
    private HashMap<String, Session> serverSessionMap = new HashMap<String, Session>();
    private static Boolean flag ;
    private Iterator it ;
    private int mapsize ;
    private String[] keys;
    int keynum ;
    String str;
    //执行参数
    String fuwuqixinxi = "";
    String nmonbushulujing = "";
    String pinglv = "";
    String cishu = "";
    String name = "";

    public StartMonitor(HashMap serverMap,HashMap serverSessionMap, int keynum,String nmonbushulujing ,String pinglv,String cishu,String name){
        this.serverMap = serverMap;
        this.serverSessionMap = serverSessionMap;
        this.keynum = keynum;
        this.flag = true;
        this.mapsize = serverMap.size();
        this.it = serverMap.keySet().iterator();
        this.keys = new String[mapsize];
        this.nmonbushulujing = nmonbushulujing;
        this.pinglv = pinglv;
        this.cishu = cishu;
        this.name = name;
        for (int i = 0; i < mapsize; i++) {
            keys[i] = it.next().toString();
        }
    }

    @Override
    public String call() throws Exception {
        String str = "";
        while (flag){
            str = startNmon();
        }
        if (str.length()>0){
            return "执行错误："+str;
        }
        return str;
    }

    private String startNmon() {
        String result = "";
        String str = getMapskey();
        try {
            //对部署路径的处理，如果存在家目录
            //用户3种情况
            /**
             * ~/myNmon 目录 普通用户  ~ 替换 /home/用户名/myNmon
             * ~/myNmon 目录 root用户 ~ 替换 /用户名/myNmon
             * /home/myNmon   不需要修改和替换
             *  to do 需添加新功能，当监控文件已存在时，自动添加后缀区分
             */
            String strlujing = nmonbushulujing;
            if (serverMap.get(str)[3].toUpperCase().contains("DEFAULT") && strlujing.contains("~/")){
                if(serverSessionMap.get(str).getUserName().toUpperCase().contains("ROOT")){
                    strlujing = strlujing.replace("~","/"+serverSessionMap.get(str).getUserName());
                }else{
                    strlujing = strlujing.replace("~","/home/"+serverSessionMap.get(str).getUserName());
                }
            }else {
                strlujing = serverMap.get(str)[3].toString();
            }
            if(execCommandByJSch(serverSessionMap.get(str), "ps -ef|grep "+name+"|grep -v grep|awk '{print $2}'").length()==0){
                //如果为linux
                if(execCommandByJSch(serverSessionMap.get(str), "uname", "UTF-8").toUpperCase().contains("LINUX")) {
                    result = execCommandByJSch(serverSessionMap.get(str), strlujing + "/nmon -F " + strlujing + "/" + serverSessionMap.get(str).getHost() + "_" + name + ".nmon" + " -s " + pinglv + " -c " + cishu +" -t", "UTF-8");
                }else if(execCommandByJSch(serverSessionMap.get(str), "uname", "UTF-8").toUpperCase().contains("AIX")) {
                    result = execCommandByJSch(serverSessionMap.get(str), "nmon -F " + strlujing + "/" + serverSessionMap.get(str).getHost() + "_" + name + ".nmon" + " -s " + pinglv + " -c " + cishu + " -t", "UTF-8");
                }
            }else{
                result = "此命名监控进程已存在";
                System.err.println(serverSessionMap.get(str)+"服务器此命名监控进程已存在");
            }

        } catch (Exception e) {
            System.err.println(serverSessionMap.get(str).getHost()+"开始监控 error："+e.getMessage());
            return e.getMessage();
        }
        return result;
    }



    public synchronized String getMapskey(){
        String key = keys[keynum];
        keynum++;
        if(keynum >= mapsize){
            flag = false;

        }
        // System.out.println("线程"+Thread.currentThread().getName()+"获取了key"+key+",此时的 keynum已经是:"+keynum );
        return key;
    }
}